<template>
  <div>
    <!-- <r-search
      :searchForm="searchForm"
      :searchHandle="searchHandle"
      :searchData="searchData"
    /> -->
    <!-- 充值套餐 -->
    <div>
      <el-dialog
        width="600px"
        title="Recharge Package"
        :visible.sync="renewalShow"
      >
        <el-form
          :model="renewalData"
          :status-icon="true"
          :rules="renewalRules"
          ref="renewalData"
          label-width="150px"
          class="renewalData"
        >
          <!-- <el-form-item label="Recharge Money" prop="type">
            <el-input v-model="renewalData.type" style="width:350px" />
          </el-form-item> -->
          <el-form-item label="umber Of days" prop="days">
            <el-input
              type="number"
              v-model="renewalData.days"
              style="width:350px"
            />
          </el-form-item>
          <el-form-item label="umber Of Times" prop="nums">
            <el-input
              type="number"
              v-model="renewalData.nums"
              style="width:350px"
            />
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="renewalShow = false">Cancel</el-button>
          <el-button type="primary" @click="renewalSubmit('renewalData')"
            >Confirm</el-button
          >
        </div>
      </el-dialog>
    </div>
    <!-- 充值金额 -->
    <div>
      <el-dialog
        width="600px"
        title="Recharge Money"
        :visible.sync="renewalShow1"
      >
        <el-form
          :model="renewalData1"
          :status-icon="true"
          :rules="renewalRules1"
          ref="renewalData1"
          label-width="150px"
          class="renewalData1"
        >
          <el-form-item label="Money" prop="money">
            <el-input
              type="number"
              v-model="renewalData1.money"
              style="width:350px"
            />
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="renewalShow1 = false">Cancel</el-button>
          <el-button type="primary" @click="renewalSubmit1('renewalData1')"
            >Confirm</el-button
          >
        </div>
      </el-dialog>
    </div>
    <r-table
      :tableHandles="tableHandles"
      :isSelection="false"
      :isIndex="false"
      :isPagination="true"
      :tableData="tableData"
      :tableCols="tableCols"
      :tablePage="tablePage"
      :isHandle="true"
      @refresh="init()"
    >
    </r-table>
    <r-form
      :formRules="formRules"
      :formHandle="formHandle"
      :formData="formData"
      :formCols="formCols"
      ref="elForm"
      labelWidth="200px"
      dialogWidth="700px"
      :isHandle="true"
    />
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 充值套餐
      renewalData: {
        icId: "",
        type: 2,
        days: "",
        nums: ""
      },
      renewalRules: {
        days: [{ required: true, message: "Please Enter", trigger: "blur" }],
        nums: [{ required: true, message: "Please Enter", trigger: "blur" }]
      },
      renewalShow: false,
      // 充值金额
      renewalData1: {
        icId: "",
        type: 1,
        money: ""
      },
      renewalRules1: {
        money: [{ required: true, message: "Please Enter", trigger: "blur" }]
      },
      renewalShow1: false,

      agentArr: [],
      isCharge: false,
      isTemporary: false,
      agentIdArr: [],
      formLabelWidth: "120px",
      agentValue: "",
      agentIdValue: [],
      inquireAgentData: [],
      searchData: {
        cardNo: ""
      },
      searchForm: [
        {
          type: "input",
          prop: "cardNo",
          placeholder: "Card Number",
          width: 240
        }
      ],
      searchHandle: [
        {
          label: "Search",
          type: "success",
          plain: true,
          icon: "el-icon-search",
          handle: e => {
            // this.zeroFn()
            this.init();
          }
        },
        {
          label: "Reset",
          buttonss: true,
          icon: "el-icon-refresh-right",
          handle: e => {
            this.searchData = {
              cardNo: ""
            };
            // this.zeroFn()
            this.init();
          }
        }
      ],

      tableHandles: [
        {
          label: "Add",
          type: "primary",
          plain: true,
          isShow: true,
          handle: e => this.elFormVisible(),
          isShow: row => {
            return sessionStorage.role == "operator" ? true : false;
          }
        }
      ],
      tableData: [],
      tableCols: [
        {
          label: "Card Number",
          prop: "cardNo"
        },
        {
          label: "User Name",
          prop: "userName"
        },
        {
          label: "Phone",
          prop: "phone"
        },
        {
          label: "Balance",
          prop: "balance",
          formatter: e => (e.balance ? "$" + e.balance : "$0")
        },

        {
          label: "Packages Number",
          prop: "mealNum",
          formatter: e => (e.mealNum == -1 ? "Unlimited Times" : e.mealNum)
        },
        {
          label: "Identity Card",
          prop: "idNumber"
        },
        {
          label: "Package Validity Period",
          prop: "validity"
        },
        {
          label: "Creation Time",
          prop: "ctime"
        },

        {
          label: "Operations",
          type: "button",
          width: 220,
          btnList: [
            {
              label: "Edit",
              type: "primary",
              size: "mini",
              plain: true,
              style: { "margin-bottom": "5px" },
              handle: row => this.elFormDetail(row)
            },
            {
              label: "Delete",
              type: "danger",
              size: "mini",
              plain: true,
              handle: row => {
                this.$confirm("Confirm Delete?", "Hint", {
                  confirmButtonText: "Confirm",
                  cancelButtonText: "Cancel",
                  type: "warning"
                })
                  .then(async () => {
                    const res = await this.apis.icDelById(row.id || "");
                    this.$message({
                      type: "success",
                      message: "Delete Success!"
                    });
                    this.init();
                  })
                  .catch(() => {});
              }
            },
            {
              label: "Recharge Package",
              type: "success",
              size: "mini",
              plain: true,
              style: { "margin-bottom": "5px" },
              handle: e => {
                this.renewalShow = true;
                this.renewalData.icId = e.id;
              }
            },
            {
              label: "Recharge Money",
              type: "success",
              size: "mini",
              plain: true,
              style: { "margin-bottom": "5px" },
              handle: e => {
                this.renewalShow1 = true;
                this.renewalData1.icId = e.id;
              }
            },
            {
              label: "Reset Money Or Packages",
              type: "primary",
              size: "mini",
              plain: true,

              handle: row => {
                this.$confirm("Confirm Reset?", "Hint", {
                  confirmButtonText: "Confirm",
                  cancelButtonText: "Cancel",
                  type: "warning"
                })
                  .then(async () => {
                    const res = await this.apis.icReset(row.id || "");
                    this.$message({
                      type: "success",
                      message: "Delete Success!"
                    });
                    this.init();
                  })
                  .catch(() => {});
              }
            }
          ]
        }
      ],
      tablePage: { limit: 10, page: 1, total: 0 },
      formData: {
        id: null, //ic卡id
        cardNo: "", //卡号
        userName: "", //用户名
        phone: "", //手机号
        idNumber: "" //身份证号
      },
      formCols: [
        // { type: "input", label: "ID", width: 350, prop: "id" },
        { type: "input", label: "Card Number", width: 350, prop: "cardNo" },
        { type: "input", label: "User Name", width: 350, prop: "userName" },
        { type: "input", label: "Phone", width: 350, prop: "phone" },
        { type: "input", label: "Identity Card", width: 350, prop: "idNumber" }
      ],
      formRules: {
        id: [{ required: true, message: "Please Enter", trigger: "blur" }],
        cardNo: [{ required: true, message: "Please Enter", trigger: "blur" }],
        userName: [
          { required: true, message: "Please Enter", trigger: "blur" }
        ],
        phone: [{ required: true, message: "Please Enter", trigger: "blur" }],
        idNumber: [{ required: true, message: "Please Enter", trigger: "blur" }]
      },
      formHandle: [
        {
          label: "Cancel",
          handle: e => this.elFormVisible()
        },
        {
          label: "Confirm",
          type: "success",
          handle: e => this.elFormSubmit()
        }
      ]
    };
  },
  components: {},
  computed: {},
  async mounted() {
    this.init();
    this.agentFn();
  },
  watch: {
    dialogFormVisible: {
      handler(newValue, oldValue) {
        if (!newValue && oldValue) {
          this.agentValue = "";
          this.agentIdValue = [];
        } else if (newValue && !oldValue) {
          this.agentValue = "";
          this.agentIdValue = [];
        }
      },
      deep: true // 深度监听
    },
    agentValue: {
      handler(newValue) {
        // console.log('新', newValue, '---旧', oldValue)
        if (newValue) {
          this.yesAgentFn(newValue);
        } else {
          return;
        }
      },
      deep: true // 深度监听
    }
  },
  methods: {
    // 充值套餐确认
    async renewalSubmit(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          let res = await this.apis.icTopUp(this.renewalData);
          this.$message({
            message: res.msg,
            type: res.code == 200 ? "success" : "error"
          });
          this.renewalShow = false;
          this.init();
        }
      });
    },
    // 充值金额确认
    async renewalSubmit1(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          let res = await this.apis.icTopUp(this.renewalData1);
          this.$message({
            message: res.msg,
            type: res.code == 200 ? "success" : "error"
          });
          this.renewalShow1 = false;
          this.init();
        } else {
          console.log(222);
        }
      });
    },

    zeroFn() {
      this.tablePage.limit = 10;
      this.tablePage.page = 1;
      this.tablePage.total = 0;
    },
    async init() {
      let parm = {
        pageNum: this.tablePage.page,
        pageSize: this.tablePage.limit,
        cardNo: this.searchData.cardNo
      };
      let res = await this.apis.icList(parm);
      if (res) {
        this.tableData = res.rows;
        this.tablePage.total = res.total;
        this.agentIdArr = [];
        this.tableData.forEach(i => {
          let testAgentArr = {
            id: i.id,
            name: i.typeName
          };
          this.agentIdArr.push(testAgentArr);
        });
      }
    },

    // 拿到Agentid列表
    async agentFn() {
      let param = {
        pageNum: 1,
        pageSize: 100
      };
      let res = await this.apis.agent_list(param);
      let arr = res.rows;
      arr.forEach(i => {
        let testAgentArr = {
          id: i.id,
          name: i.name
        };
        this.agentArr.push(testAgentArr);
      });
    },

    // 获取Agent电池Type列表
    async yesAgentFn(id) {
      this.agentIdValue = [];
      let res = await this.apis.batteryTypeListBatteryTypeByAgent(id);
      this.inquireAgentData = res.data || [];
      if (res.code == 200 && res.data.length !== 0) {
        res.data.forEach(i => {
          this.agentIdValue.push(i.id);
        });
      }
      console.log(9999, this.inquireAgentData);
    },
    async affirmAgentFn() {
      if (!this.agentValue) {
        this.$message({
          message: "Please Select Agent",
          type: "error"
        });
        return false;
      }
      if (this.agentIdValue.length === 0) {
        this.$message({
          message: "Please Select Battery Type",
          type: "error"
        });
        return false;
      }

      let params = {
        agentId: this.agentValue,
        batteryTypeIds: this.agentIdValue
      };
      let res = await this.apis.batteryTypeAddAgentBatteryType(params);
      this.$message({
        type: res.code == 200 ? "success" : "error",
        message: res.msg
      });
      this.dialogFormVisible = false;
    },

    async elFormSubmit() {
      this.$refs.elForm.$refs.ruleForm.validate(async valid => {
        if (valid) {
          if (this.formData.id) {
            let res = await this.apis.icEdit(this.formData);
            if (res) {
              this.init();
              this.elFormVisible();
              this.$message({
                message: res.msg,
                type: res.code === 200 ? "success" : "error"
              });
            }
          } else {
            let res = await this.apis.icSave(this.formData);
            if (res) {
              this.init();
              this.elFormVisible();
              this.$message({
                message: res.msg,
                type: res.code === 200 ? "success" : "error"
              });
            }
          }
        }
      });
    },
    async changestate(id) {
      let res = await this.api.packchange({ id });
      if (res) {
        this.init();
      }
    },
    elFormDetail(row) {
      Object.keys(this.formData).forEach(key => {
        this.formData[key] = row[key];
      });
      this.formData.id = row.id;
      this.elFormVisible();
    }
  }
};
</script>
<style scoped lang="scss">
.el-icon-search {
  margin-right: 10px;
}

.Tip {
  margin-left: 20px;
}
</style>
